package com.starblink.wishlist.detailsadd.ui

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.viewModelScope
import com.apollographql.apollo3.api.Optional
import com.starblink.android.basic.base.BaseViewModel
import com.starblink.android.basic.ext.string
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.toastUI
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.basic.apollo.ext.optional
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.rocketreserver.MoveProductList2WishListMutation
import com.starblink.rocketreserver.PageQueryMyCollectProductsQuery
import com.starblink.rocketreserver.type.CollectItem
import com.starblink.rocketreserver.type.PageQuery4CollectProductReq
import com.starblink.wishlist.wishallitems.ui.bean.RvNormalEmpty
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry
import kotlinx.coroutines.launch

class DetailsAddVM : BaseViewModel() {

    var mAllItemsObserver: MutableLiveData<ArrayList<Any>> = MutableLiveData()
    var pageTopIndex = 1
    var pageTopSize = 20
    var curKeyword = ""
    var wishId: String? = null

    fun initSomeData(wishId: String) {
        this.wishId = wishId
        if (mAllItemsObserver.value == null) {
            mAllItemsObserver.value = arrayListOf()
        }
    }

    inline fun refreshData(showDialog: Boolean = false, crossinline hasFinish: () -> Unit) {
        viewModelScope.launch {
            pageTopIndex = 1
            val wishResult = SkGqlClient.skQuery(
                PageQueryMyCollectProductsQuery(
                    pageQuery4CollectProduct = PageQuery4CollectProductReq(
                        wishListId = 0,
                        toWishListId = Optional.present(wishId!!),
                        needFilterResultList = Optional.present(false),
                        pageNo = pageTopIndex.optional(),
                        pageSize = Optional.present(pageTopSize),
                        title = Optional.present(curKeyword)
                    )
                ),
                showDefaultLoading = showDialog
                //fetchPolicy = FetchPolicy.NetworkFirst
            )?.data?.pageQueryMyCollectProducts

            wishResult.let {
                mAllItemsObserver.value!!.clear()
                // 列表数据
                if (!it?.productList.isNullOrEmpty()) {
                    it!!.productList!!.forEach { prdList ->
                        mAllItemsObserver.value!!.add(
                            RvBoardDetailsItemEntry(
                                wishItem = prdList.productF,
//                                position = mAllItemsObserver.value!!.size
                            )
                        )
                    }
                } else {
                    mAllItemsObserver.value!!.add(RvNormalEmpty())
                }
                mAllItemsObserver.postValue(mAllItemsObserver.value)
                hasFinish()
            }
        }
    }


    inline fun loadMoreData(crossinline hasFinish: () -> Unit) {
        viewModelScope.launch {
            pageTopIndex++
            val wishResult = SkGqlClient.skQuery(
                PageQueryMyCollectProductsQuery(
                    pageQuery4CollectProduct = PageQuery4CollectProductReq(
                        wishListId = 0,
                        toWishListId = Optional.present(wishId!!),
                        needFilterResultList = Optional.present(false),
                        pageNo = pageTopIndex.optional(),
                        pageSize = Optional.present(pageTopSize),
                        title = Optional.present(curKeyword),
                    )
                ),
                //fetchPolicy = FetchPolicy.NetworkFirst
            )?.data?.pageQueryMyCollectProducts
            wishResult.let {
                // 列表数据
                if (!it?.productList.isNullOrEmpty()) {
                    it!!.productList!!.forEach { prdList ->
                        mAllItemsObserver.value!!.add(
                            RvBoardDetailsItemEntry(
                                wishItem = prdList.productF,
//                                position = mAllItemsObserver.value!!.size
                            )
                        )
                    }
                } else {
//                    toastUI(CommUtils.getString(R.string.no_more_data))
                }
                mAllItemsObserver.postValue(mAllItemsObserver.value)
                hasFinish()
            }
        }
    }


    fun hasChoice(): Boolean {
        var choice = false
        for ((index, item) in mAllItemsObserver.value!!.withIndex()) {
            if (item is RvBoardDetailsItemEntry) {
                if (item.hasChoice) {
                    choice = true
                    break
                }
            }
        }
        return choice
    }


    fun move2Wishlist(hasFinish: () -> Unit) {
        var num = 0
        viewModelScope.launch {
            val data = SkGqlClient.skMutation(
                MoveProductList2WishListMutation(
                    items = arrayListOf<CollectItem>().apply {
                        mAllItemsObserver.value!!.forEach {
                            if (it is RvBoardDetailsItemEntry && it.hasChoice) {
                                add(
                                    CollectItem(
                                        id = it.wishItem.id!!,
                                        type = it.wishItem.type.optional(),
                                    )
                                )
                                num++
                            }
                        }
                    }.optional(),
                    fromWishListId = Optional.Absent,
                    toWishListId = wishId!!.optional(),
                ),
                showDefaultLoading = true,
            )
            val success = data?.data?.moveProductList2WishList == true
            if (success) {
                FlowBus.boolFlowBusNotify(FlowConst.WISHLIST_BOARD_REFRESH)
                FlowBus.with<Int>(FlowConst.WISHLIST_ADD_DETAILS_SELECT_PAGE).post(num)
                hasFinish.invoke()
            } else {
                data?.errors?.getOrNull(0)?.message?.let {
                    toast(it)
                }
            }
        }
    }

}